package com.vm.osm.business.common;

import com.vm.osm.business.dto.rsp.RspError;
import com.vm.osm.business.util.GsonUtil;
import com.vm.osm.business.util.UserDataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录验证拦截器
 *
 * @author Xuerong Xue
 */
public class ValidLogonInterceptor extends HandlerInterceptorAdapter {
    protected Logger LOG = LoggerFactory.getLogger(ValidLogonInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) return true;
        HandlerMethod method = (HandlerMethod) handler;
        ValidLogon validation = method.getMethodAnnotation(ValidLogon.class);
        if (null == validation) {
            return true;
        }
        String staff_id = UserDataUtil.getStaffId(request);
        if (!StringUtils.isEmpty(staff_id)) return true;
        LOG.warn("【登录验证】用户未登录");
        RspError error = new RspError();
        error.setErr_code(ErrCode.NOT_AUTH_FAIL);
        error.setErr_msg("用户未登录");
        error.setRequest_id(MDC.get("requestId"));
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        PrintWriter writer = response.getWriter();
        writer.print(GsonUtil.toJson(error));
        return false;
    }
}
